﻿using Aker.AkerDBTableAdapters;
using DevExpress.XtraEditors;
using DevTeam;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Windows.Forms;

namespace Aker.DevTeam
{
    public class Data
    {
        public static BindingSource bsProduct;
        public static BindingSource bsOrder;
        public static BindingSource bsOrderLines;
        public static BindingSource bsCustomer;
        public static BindingSource bsPOrder;
        public static BindingSource bsPOrderLines;

        static List<string> OriginalColumns;
        //public static string[] ProductDetails = new string[] { "Article", "Design", "Composition", "Width", "Weight", "PriceDollar", "PriceEuro", "Price2Dollar", "Price2Euro", "Price3Dollar", "Price3Euro" };
        public static string[] ProductDetails = new string[] { "Article", "Design", "Composition", "Width", "Weight", "FiyatExtra" };
        public static TableAdapterManager TAM = new TableAdapterManager();

        public static DataManager DM { get; set; }
        public static DataManager DMLocal { get; set; }

        private static DataManager dmServer;
        public static DataManager DMServer
        {
            get
            {
                if (dmServer == null)
                {
                    Aker.ceGate.ceGateSoapClient gate = new ceGate.ceGateSoapClient();

                    DataTable dtCredentials;
                    try
                    {
                        dtCredentials = gate.GetAkerCredentials(AppSession.UserInfo.UserName, AppSession.UserInfo.Password, "confexpert.karbel.com");
                    }
                    catch (Exception ex)
                    {
                        throw new ApplicationException(Language.Data.NoConnection);
                    }

                    if (dtCredentials == null)
                    {
                        throw new ApplicationException(Language.Data.NoSecurity);
                    }

                    string connectionString = dtCredentials.Rows[0]["ConnectionString"].ToString();
                    dmServer = new DataManager(connectionString);
                }

                return dmServer;
            }
        }


        public static AkerDB DB
        { get; set; }


        public static string LocalConnectionString
        {
            get
            {

                string ConnectionString = "Data Source=.\\sqlExpress;Initial Catalog=Aker;User ID=AkerUser;Password=10341518;Persist Security Info=True";
                //if (Environment.MachineName.ToUpper() == "KGULCAN" || Environment.MachineName.ToUpper() == "AKERDEPO" || Environment.MachineName.ToUpper() == "AKR-1020")
                //{
                //    ConnectionString = ConnectionString.Replace("Data Source=.;", "Data Source=.\\sqlExpress;");
                //}
                return ConnectionString;
            }
        }


        public static void Init(string ConnectionString)
        {
            DM = new DataManager(ConnectionString);
            DMLocal = new DataManager(Data.LocalConnectionString);


            PropertyInfo[] props = Properties.Settings.Default.GetType().GetProperties();
            foreach (PropertyInfo prop in props)
            {
                SettingsProperty sett = Properties.Settings.Default.Properties[prop.Name];
                if (sett != null)
                {
                    Properties.Settings.Default[prop.Name] = ConnectionString;
                }
            }

            DB = new Aker.AkerDB();

            TAM.ProductTableAdapter = new ProductTableAdapter();
            TAM.BusinessCardTableAdapter = new BusinessCardTableAdapter();
            TAM.OrderTableAdapter = new OrderTableAdapter();
            TAM.OrderLinesTableAdapter = new OrderLinesTableAdapter();
            TAM.SettingTableAdapter = new SettingTableAdapter();
            TAM.KullaniciTableAdapter = new KullaniciTableAdapter();
            TAM.HammaddeTableAdapter = new HammaddeTableAdapter();
            TAM.RollTableAdapter = new RollTableAdapter();
            TAM.ShelfTableAdapter = new ShelfTableAdapter();
            TAM.KullaniciSettingTableAdapter = new KullaniciSettingTableAdapter();
            TAM.UserSettingTableAdapter = new UserSettingTableAdapter();
            TAM.UreticiBarkodTableAdapter = new UreticiBarkodTableAdapter();

            TAM.CikisTableAdapter = new CikisTableAdapter();
            TAM.CikisLinesTableAdapter = new CikisLinesTableAdapter();
            TAM.DepoTableAdapter = new DepoTableAdapter();

            TAM.POrderTableAdapter = new POrderTableAdapter();
            TAM.POrderLinesTableAdapter = new POrderLinesTableAdapter();

            TAM.ElyafTableAdapter = new ElyafTableAdapter();
            TAM.ElyafGrupTableAdapter = new ElyafGrupTableAdapter();

            TAM.StokLinesTableAdapter = new StokLinesTableAdapter();


            TAM.TedarikciTableAdapter = new TedarikciTableAdapter();
            TAM.BoyahaneTableAdapter = new BoyahaneTableAdapter();

            TAM.ProductHammaddeTableAdapter = new ProductHammaddeTableAdapter();
            TAM.ProductMaliyetTableAdapter = new ProductMaliyetTableAdapter();
            TAM.ProductDetayTableAdapter = new ProductDetayTableAdapter();
            TAM.CurrencyTableAdapter = new CurrencyTableAdapter();
            TAM.OrmeMakinesiTableAdapter = new OrmeMakinesiTableAdapter();


            TAM.ElyafCekimTableAdapter = new ElyafCekimTableAdapter();
            TAM.ElyafCinsTableAdapter = new ElyafCinsTableAdapter();

            TAM.ElyafKesitTableAdapter = new ElyafKesitTableAdapter();
            TAM.ElyafKullanimTableAdapter = new ElyafKullanimTableAdapter();
            TAM.ElyafParlaklikTableAdapter = new ElyafParlaklikTableAdapter();

            TAM.ElyafRenkTableAdapter = new ElyafRenkTableAdapter();


            TAM.IplikKarisimTableAdapter = new IplikKarisimTableAdapter();
            TAM.IplikCekimTableAdapter = new IplikCekimTableAdapter();
            TAM.IplikCekmeTipiTableAdapter = new IplikCekmeTipiTableAdapter();
            TAM.IplikParlaklikTableAdapter = new IplikParlaklikTableAdapter();
            TAM.IplikFantaziTableAdapter = new IplikFantaziTableAdapter();

            TAM.IplikTableAdapter = new IplikTableAdapter();
            TAM.IplikGrupTableAdapter = new IplikGrupTableAdapter();
            TAM.IplikRenkTableAdapter = new IplikRenkTableAdapter();

            TAM.TaskTableAdapter = new TaskTableAdapter();
            TAM.AcentaTableAdapter = new AcentaTableAdapter();
            TAM.StatusTableAdapter = new StatusTableAdapter();
            TAM.CustomerTableAdapter = new CustomerTableAdapter();

            TAM.StatusTableAdapter.Fill(DB.Status);
            TAM.CustomerTableAdapter.Fill(DB.Customer);
            TAM.CariAktarimTableAdapter = new CariAktarimTableAdapter();

            TAM.CikisEmriLinesTableAdapter = new CikisEmriLinesTableAdapter();

            TAM.CikisEmriLinesTableAdapter = new CikisEmriLinesTableAdapter();

            bsProduct = new BindingSource(Data.DB, "Product");
            bsOrder = new BindingSource(Data.DB, "Order");
            bsOrderLines = new BindingSource(bsOrder, "FK_OrderLines_Order_OrderId");

            bsPOrder = new BindingSource(Data.DB, "POrder");
            bsPOrderLines = new BindingSource(bsPOrder, "FK_POrder_POrderLines_POrderId");

            bsCustomer = new BindingSource(Data.DB, "Customer");

            InitProduct();

            Cikislar.CikisSepet.Init();

            foreach (string col in ProductDetails)
            {
                DB.OrderLines.Columns.Add(col, typeof(string));
                DB.POrderLines.Columns.Add(col, typeof(string));
            }


            InitLookup();
        }



        public static void RestoreDatabaseSMO(string targetConnectionString, String backUpFile)
        {
            //SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(targetConnectionString);
            //ServerConnection connection = new ServerConnection(csb.DataSource, csb.UserID, csb.Password);
            //Server sqlServer = new Server(connection);
            //Restore rstDatabase = new Restore();
            //rstDatabase.Action = RestoreActionType.Database;
            //rstDatabase.Database = csb.InitialCatalog;
            //BackupDeviceItem bkpDevice = new BackupDeviceItem(backUpFile, DeviceType.File);
            //rstDatabase.Devices.Add(bkpDevice);
            //rstDatabase.ReplaceDatabase = true;

            //Database db = sqlServer.Databases[csb.InitialCatalog];
            //string f  = db.PrimaryFilePath;

            //string dataFile = db.FileGroups[0].Files[0].FileName;
            //string logFile = db.LogFiles[0].FileName;

            ////rstDatabase.RelocateFiles.Add(new RelocateFile(csb.InitialCatalog, dataFile ));
            ////rstDatabase.RelocateFiles.Add(new RelocateFile(csb.InitialCatalog, logFile));

            //System.Data.DataTable logicalRestoreFiles = rstDatabase.ReadFileList(sqlServer);
            //rstDatabase.RelocateFiles.Add(new RelocateFile(logicalRestoreFiles.Rows[0][0].ToString(), dataFile));
            //rstDatabase.RelocateFiles.Add(new RelocateFile(logicalRestoreFiles.Rows[1][0].ToString(), logFile));

            //sqlServer.KillAllProcesses(rstDatabase.Database);

            //rstDatabase.SqlRestore(sqlServer);
        }

        public static void RestoreDatabase(string targetConnectionString, String backUpFile)
        {
            targetConnectionString = targetConnectionString.Replace("Initial Catalog=Aker", "Initial Catalog=Master");
            string folder = "c:\\Aker\\";
            DataManager DMTarget = new DataManager(targetConnectionString);
            DMTarget.ExecuteDataTableByQuery("ALTER DATABASE AKER SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

            string tsql = "RESTORE DATABASE Aker FROM  DISK = N'" + backUpFile + "' WITH  FILE = 1,  MOVE N'Aker' TO N'" + folder + "Aker.mdf',  MOVE N'Aker_log' TO N'" + folder + "Aker_log.ldf',  NOUNLOAD,  REPLACE,  STATS = 5";
            DMTarget.ExecuteDataTableByQuery(tsql);

            DMTarget.ExecuteDataTableByQuery("ALTER DATABASE Aker SET MULTI_USER");
        }

        public static void PrepareOfflineFromServer()
        {
            string backupFile = "c:\\Aker\\server.bak";
            Directory.CreateDirectory("c:\\Aker");
            DM.ExecuteNonQuery("RefreshSentezData");
            byte[] backupBytes = (byte[])DM.ExecuteDataTable("GetServerBackup").Rows[0][0];

            File.WriteAllBytes(backupFile, backupBytes);

            PrepareOfflineFromFile(backupFile);
        }

        public static void PrepareOfflineFromFile(string backupFile)
        {
            RestoreDatabase(LocalConnectionString, backupFile);

            DataManager dm = new DataManager(LocalConnectionString);
            dm.ExecuteDataTableByQuery("Update Setting set Value = '" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' where SettingId = 14");
            dm.ExecuteNonQuery("update [Order] set SyncDate = getdate() where syncDate is null");

            XtraMessageBox.Show("Ready for fair !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }









        private static BackgroundWorker bwRefresher = new BackgroundWorker();
        private static System.Timers.Timer timer;



        public static List<int> ModifiedProducts = new List<int>();

        public static bool IsLookupInitialized = false;
        public delegate void LookupInitializedHandler();
        public static event LookupInitializedHandler LookupInitialized;



        private static void InitLookup()
        {
            bwRefresher.DoWork += bwRefresher_DoWork;
            bwRefresher.RunWorkerCompleted += bwRefresher_RunWorkerCompleted;

            timer = new System.Timers.Timer(1 * 1000 * 10);
            timer.SynchronizingObject = AppSession.MainForm;
            timer.Elapsed += RaiseUpdate;
            timer.Enabled = true;
        }


        static void bwRefresher_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                System.Diagnostics.Debug.WriteLine("BW Completed");
                DataSet updates = (DataSet)e.Result;
                DataTable dtProduct = updates.Tables[0];
                if (dtProduct.Rows.Count > 0)
                    Data.DB.Product.Merge(dtProduct);

                if (!IsLookupInitialized) //First time
                {
                    //if (DB.Product.Count == 0)
                    //    TAM.ProductTableAdapter.Fill(DB.Product);

                    foreach (DataRow dr in DB.Product)
                        dr["Select"] = false;

                    DB.Product.AcceptChanges();

                    //ModifiedProducts.Clear();
                    IsLookupInitialized = true;
                    AppSession.MainForm.Info = "Artikeller yüklendi.";

                    if (LookupInitialized != null)
                        LookupInitialized();
                }
                else
                {
                    foreach (DataRow dr in dtProduct.Rows)
                    {
                        int productId = (int)dr["ProductId"];
                        if (!ModifiedProducts.Contains(productId))
                            ModifiedProducts.Add(productId);
                    }
                }
            }
        }

        private static void RaiseUpdate(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Enabled = false;
            RefreshData();
            timer.Enabled = true;
        }

        public static void RefreshData()
        {
            if (!bwRefresher.IsBusy)
                bwRefresher.RunWorkerAsync();
        }

        static void bwRefresher_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("DoWork");
                DateTime LastModified = new DateTime(2000, 1, 1);

                //foreach (Aker.AkerDB.ProductRow dr in Data.DB.Product.Rows)
                //    if (!dr.IsModifiedOnNull() && dr.ModifiedOn > LastModified)
                //        LastModified = dr.ModifiedOn;

                //aynı anda değişmesin diye kopyası alınıyor
                object result = Data.DB.Product.Copy().Compute("Max(ModifiedOn)", "");
                if (result != DBNull.Value)
                    LastModified = (DateTime)result;

                e.Result = Data.GetUpdates(LastModified);
            }
            catch (Exception ex)
            {
                //throw ex;
                LogManager.LogToDB(ex, "AutoUpdate çalışmadı.");
            }
        }



        public static void aFillProducts()
        {
            //AppSession.MainForm.FirstLoad += MainForm_FirstLoad;
            //TODO: Fill yapınca farklı formlardan açık olan product varsa onların da selected ı false oluyor.
            //var timer = new DispatcherTimer();
            //timer.Tick += delegate
            //{
            //    if (AppSession.MainForm.FirstTimeLoaded)
            //    {


            //        timer.Stop();
            //    }
            //};

            //timer.Interval = TimeSpan.FromMilliseconds(1000);
            //timer.Start();

            //DB.Product.Clear();
            //while (!AppSession.MainForm.FirstTimeLoaded)
            //{
            //    System.Threading.Thread.Sleep(1000);
            //}

            //if (DB.Product.Count == 0)
            //    TAM.ProductTableAdapter.Fill(DB.Product);

            //foreach (DataRow dr in DB.Product)
            //{
            //    dr["Select"] = false;
            //}

            //DataTable dtStock = DM.ExecuteDataTable("GetProductStock");
            //foreach (DataRow dr in dtStock.Rows)
            //{
            //    int productId = (int)dr["ProductId"];
            //    AkerDB.ProductRow drProduct = Data.DB.Product.FindByProductId(productId);
            //    drProduct["Qty"] = dr["Qty"];
            //    drProduct["RollCount"] = dr["RollCount"];
            //}

            //DB.Product.AcceptChanges();
        }











        public static string GetSetting(int SettingId)
        {
            return DB.Setting.FindBySettingId(SettingId)["Value"].ToStringNN().Replace("?<!DOCTYPE", "<!DOCTYPE");
        }

        public static void SetSetting(int SettingId, string value)
        {
            DB.Setting.FindBySettingId(SettingId)["Value"] = value;
        }



        private static void InitProduct()
        {
            OriginalColumns = new List<string>();
            foreach (DataColumn dc in DB.Product.Columns)
                OriginalColumns.Add(dc.ColumnName);

            //Add runtime columns
            DB.Product.Columns.Add("Select", typeof(bool));
            DB.Product.Columns.Add("Order", typeof(int));
            DB.Product.Columns.Add("PrintCount", typeof(int));
            DB.Product.Columns.Add("RollCount", typeof(int));
            DB.Product.Columns.Add("Qty", typeof(decimal));


            foreach (DataRow dr in DB.Product.Rows)
                dr["Select"] = false;

            DB.Product.TableNewRow += Product_TableNewRow;

            DB.Product.AcceptChanges();
        }

        private static void Product_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["Select"] = false;
        }

        public static void SaveProduct(DataRow dr)
        {
            bsProduct.EndEdit();

            Data.TAM.ProductTableAdapter.Update(dr);
        }

        public static void SaveOrderOrderLines()
        {
            bsOrder.EndEdit();
            bsOrderLines.EndEdit();

            Data.TAM.OrderLinesTableAdapter.Update(DB.OrderLines);
            Data.TAM.OrderTableAdapter.Update(DB.Order);

        }

        public static void SaveOrder()
        {
            bsOrder.EndEdit();

            Data.TAM.OrderTableAdapter.Update(DB.Order);
        }

        public static void SaveOrder(DataRow dr)
        {
            bsOrder.EndEdit();

            Data.TAM.OrderTableAdapter.Update(dr);
        }

        public static void SaveOrderLines()
        {
            bsOrderLines.EndEdit();

            AkerDB.OrderLinesDataTable d = DB.OrderLines;
            Data.TAM.OrderLinesTableAdapter.Update(DB.OrderLines);
        }



        public static string Sync(DataRow[] drs)
        {
            string error = "";
            int lastIndex = 0;
            if (drs.Length > 0)
            {
                foreach (DataRow dr in drs)
                {
                    try
                    {
                        int orderId = int.Parse(dr["OrderId"].ToString());
                        DataSet ds = Data.DM.ExecuteDataSet("GetSyncData", orderId);

                        object bc = DBNull.Value;

                        if (ds.Tables[2].Rows.Count == 1)
                            bc = (byte[])ds.Tables[2].Rows[0]["BusinessCard"];


                        bool exists = (bool)Data.DMServer.ExecuteScalar("IsSyncOrderExists", Settings.TerminalNo, orderId);

                        string strOrder = ds.Tables[0].Serialize();
                        string strOrderLines = ds.Tables[1].Serialize();
                        DateTime syncDate = DateTime.Now;

                        if (!exists)
                        {
                            Data.DMServer.ExecuteNonQuery("Sync", syncDate, strOrder, strOrderLines, bc);

                            dr["SyncDate"] = syncDate;
                            lastIndex++;
                        }
                        else
                        {
                            DialogResult ask = XtraMessageBox.Show(Language.Data.OverWrite, Language.Uyari, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                            if (ask == DialogResult.Yes)
                            {
                                Data.DMServer.ExecuteNonQuery("Sync", syncDate, strOrder, strOrderLines, bc);

                                dr["SyncDate"] = syncDate;
                                lastIndex++;
                            }
                        }


                    }
                    catch (ApplicationException ex)
                    {
                        error = ex.ToString();
                        break;
                    }
                }

                Data.SaveOrder();

            }

            return error + Language.Data.SyncCompleted + lastIndex.ToString() + Language.Data.Items;
        }

        public static string SendEmail(DataRow[] drs)
        {
            string error = "";
            int lastIndex = 0;
            bool eng = false;
            bool showroom = false;
            bool includePhotos = false;

            if (drs.Length > 0)
            {
                foreach (DataRow dr in drs)
                {
                    showroom = (bool)dr["Showroom"];
                    includePhotos = (bool)dr["IncludePhoto"];

                    try
                    {
                        string body = Settings.Mail_Showroom_EN_Body;
                        string subject = Settings.Mail_Showroom_EN_Subject;

                        if (showroom)
                        {
                            if (dr["Country"].ToStringNN() == "Turkey")
                            {
                                body = Settings.Mail_Showroom_TR_Body;
                                subject = Settings.Mail_Showroom_TR_Subject;
                            }
                            else
                            {
                                body = Settings.Mail_Showroom_EN_Body;
                                subject = Settings.Mail_Showroom_EN_Subject;
                                eng = true;
                            }
                        }
                        else
                        {
                            if (dr["Country"].ToStringNN() == "Turkey")
                            {
                                body = Settings.Mail_Fair_TR_Body;
                                subject = Settings.Mail_Fair_TR_Subject;
                            }
                            else
                            {
                                body = Settings.Mail_Fair_EN_Body;
                                subject = Settings.Mail_Fair_EN_Subject;
                                eng = true;
                            }
                        }



                        int selectedOrderId = (int)dr["OrderId"];

                        string reference = "AKR-" + Settings.FairNo + "-" + Settings.TerminalNo + "-" + selectedOrderId.ToString().PadLeft(4, '0');
                        string FileName = reference + ".pdf";

                        string Brand = "";
                        if (dr["Brand"] != DBNull.Value && dr["Brand"] != null)
                            Brand = (string)dr["Brand"];

                        string Subject = subject.Replace("[BRAND]", Brand).Replace("[FAIR]", Settings.FairName);

                        DataSet dsReport = Data.DM.ExecuteDataSet("GetOrderReport", selectedOrderId, Settings.TerminalNo, Settings.FairNo);
                        OrderReport or = new OrderReport(dsReport, false, eng, includePhotos);
                        string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + "\\" + FileName;
                        or.ExportToPdf(FilePath);
                        Stream stream = new MemoryStream(File.ReadAllBytes(FilePath));

                        string To = "";
                        if (dr["Email"] != DBNull.Value && dr["Email"] != null)
                        {
                            To = (string)dr["Email"];

                            foreach (string email in To.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                            {
                                if (!email.IsValidEmail())
                                {
                                    XtraMessageBox.Show(Language.Data.WrongMail + email);
                                    return "";
                                }
                            }
                        }

                        string contact = "";
                        if (dr["Contact"] != DBNull.Value && dr["Contact"] != null)
                            contact = (string)dr["Contact"];

                        string[] tos = To.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        string[] contacts = contact.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                        if (tos.Length != contacts.Length)
                        {
                            XtraMessageBox.Show(Language.Data.CountProblem);
                            continue;
                        }


                        List<MailMessage> mails = new List<MailMessage>();
                        for (int i = 0; i < tos.Length; i++)
                        {
                            MailMessage email = new MailMessage();
                            email.From = new MailAddress("fair@akertekstil.com", "Aker Tekstil Kumascilik");

                            email.Subject = Subject;
                            email.Body = body.Replace("[NAME]", contacts[i].Trim()).Replace("[BRAND]", Brand).Replace("[FAIR]", Settings.FairName).Replace("[FAIRNO]", Settings.FairNo);

                            email.IsBodyHtml = true;
                            email.To.Add(tos[i].Trim());
                            if (i == 0)
                                email.Bcc.Add("fair@akertekstil.com");
                            email.Attachments.Add(new Attachment(stream, FileName));
                            mails.Add(email);
                        }

                        try
                        {
                            using (SmtpClient emailClient = new SmtpClient("smtp.office365.com", 587))
                            {
                                emailClient.Credentials = new NetworkCredential("fair@akertekstil.com", "Dajo8509");
                                emailClient.EnableSsl = true;

                                foreach (MailMessage mail in mails)
                                    emailClient.Send(mail);

                                Data.DB.Order.Select("OrderId = " + selectedOrderId)[0]["eMailDate"] = DateTime.Now;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new ApplicationException(Language.Data.MailError + ex.ToString() + "...");
                        }
                        lastIndex++;
                    }
                    catch (ApplicationException ex)
                    {
                        error = ex.ToString();
                        break;
                    }
                }

                Data.SaveOrder();
                error = error + Language.Data.MailCompleted + lastIndex.ToString() + Language.Data.Items;
            }
            return error;
        }

        public static DataSet GetUpdates(DateTime lastModifiedOn)
        {
            return DM.ExecuteDataSet("GetUpdates", lastModifiedOn);
        }



        public static string GetUserSetting(int SettingId)
        {
            DataRow[] drs = DB.KullaniciSetting.Select("KullaniciId=" + AppSession.UserInfo.UserId + " and SettingId=" + SettingId);
            if (drs.Length == 0)
                return "";
            else
                return drs[0]["Deger"].ToStringNN();
        }

        public static void SetUserSetting(int SettingId, string value)
        {
            DataRow[] drs = DB.KullaniciSetting.Select("KullaniciId=" + AppSession.UserInfo.UserId + " and SettingId=" + SettingId);
            if (drs.Length == 0)
            {
                DB.KullaniciSetting.AddKullaniciSettingRow(AppSession.UserInfo.UserId, SettingId, value);
            }
            else
            {
                drs[0]["Deger"] = value;
            }

        }

    }
}